﻿using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Anmlz.Web.Filters
{
    using System.Globalization;

    using Anmlz.Services;
    using Anmlz.Services.Contracts;

    public class LanguageDetectionAttribute : IActionFilter
    {
        private const string LanguageCookieName = "language";
        private readonly ILanguageService _languageService;

        public LanguageDetectionAttribute()
        {
            _languageService = DependencyResolver.Current.GetService<ILanguageService>();
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var cookie = HttpContext.Current.Request.Cookies.Get(LanguageCookieName);
            if (cookie != null)
            {
                string cultureTwoLetterName = cookie.Value.ToString(CultureInfo.InvariantCulture);

                switch (cultureTwoLetterName)
                {
                    case CultureNames.English:
                    case CultureNames.Russian:
                        _languageService.SetCurrentLanguage(cultureTwoLetterName);
                        return;
                }
            }
            if (HttpContext.Current.Request.UserLanguages == null)
            {
                return;
            }
            string langRaw = HttpContext.Current.Request.UserLanguages.First();
            var cultureName = langRaw.Substring(0, 2);
            this._languageService.SetCurrentLanguage(cultureName);
        }

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
           
        }
    }

}